import WebIM from "./WebIM.js";



function IM({
	userInfo,
	vm
}) {
	this.userInfo = userInfo;
	this.vm = vm;
	// this.userId = this.userInfo.id;
	this.userId = this.userInfo.phone;
	this.imageAllowType = {
		jpg: true,
		jpeg: true,
		gif: true,
		png: true,
		bmp: true
	};
}

IM.prototype.listen = function() {
	let _this = this;
	WebIM.conn.listen({
		onOpened: () => {
			console.log('链接成功')
		}, //连接成功回调 
		onClosed: () => {
			console.log("1111111111111111111111111")
			// this.vm.$websocketStatus = new Promise((resolve, reject) => {
			// 	this.vm.$websocketConnect = resolve;
			// })
			// console.log(this.vm.$websocketStatus)
			// if (this.vm.networkStatus == 'none') {

			// } else if (this.vm._route.path == '/pages/login_entry/loginEntry') {
			// 	return 
			// }else{

			// }
		},
		//连接关闭回调
		onTextMessage: async (message) => {
			console.log(message)
			if (message.ext.business) {
				console.log('收到开通会员信息通知')
				const {
					data
				} = await this.vm.$u.post(this.vm.$restUrl.getUserInfo);
				if (data) this.vm.$u.localSave('userInfo', data);
				return
			}
			this.vm.$set(message, 'type', this.getType(message.type))
			uni.$emit('onMessage', message);
			uni.$emit('sessionListOnMessage', message);
		}, //收到文本消息
		onEmojiMessage: function(message) {}, //收到表情消息
		onPictureMessage: (message) => {
			this.vm.$set(message, 'type', this.getType(message.type))
			uni.$emit('onMessage', message);
			uni.$emit('sessionListOnMessage', message);
		}, //收到图片消息
		onCmdMessage: function(message) {}, //收到命令消息
		onAudioMessage: (message) => {
			this.vm.$set(message, 'type', this.getType(message.type))
			uni.$emit('onMessage', message);
			uni.$emit('sessionListOnMessage', message);
		}, //收到音频消息
		onLocationMessage: function(message) {}, //收到位置消息
		onFileMessage: function(message) {}, //收到文件消息
		onCustomMessage: (message) => {
			this.vm.$set(message, 'type', this.getType(message.type))
			uni.$emit('onMessage', message);
			uni.$emit('sessionListOnMessage', message);
		}, //收到自定义消息
		onVideoMessage: function(message) {
			var node = document.getElementById('privateVideo');
			var option = {
				url: message.url,
				headers: {
					'Accept': 'audio/mp4'
				},
				onFileDownloadComplete: function(response) {
					var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
					node.src = objectURL;
				},
				onFileDownloadError: function() {
					console.log('File down load error.')
				}
			};
			WebIM.utils.download.call(conn, option);
		}, //收到视频消息
		onPresence: function(message) {}, //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
		onRoster: function(message) {}, //处理好友申请
		onInviteMessage: function(message) {}, //处理群组邀请
		onOnline: function() {}, //本机网络连接成功
		onOffline: function() {
			console.log('网络掉线')
		}, //本机网络掉线
		onError: function(message) {}, //失败回调
		onBlacklistUpdate: function(list) { //黑名单变动
			// 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
			console.log(list);
		},
		onRecallMessage: (message) => {
			uni.$emit('onWithdrawMsg', message);
		}, //收到撤回消息回调
		onReceivedMessage: function(message) {}, //收到消息送达服务器回执
		onDeliveredMessage: function(message) {}, //收到消息送达客户端回执
		onReadMessage: function(message) {}, //收到消息已读回执
		onCreateGroup: function(message) {}, //创建群组成功回执（需调用createGroupNew）
		onMutedMessage: function(message) {}, //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
		onChannelMessage: function(message) {} //收到整个会话已读的回执，在对方发送channel ack时会在这个回调里收到消息
	});
}


IM.prototype.watchLoginState = function() {

	this.vm.loginState = uni.WebIM.conn.logOut;
	console.log(this.vm.loginState)
	this.vm.$watch('loginState', (val, oval) => {
		console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>websocket登录状态', val);
	}, {
		immediate: true
	})
}


IM.prototype.loginByToken = function() {
	console.log(this)
	const options = {
		user: this.userId,
		accessToken: this.vm.getHXTokenSync(),
		appKey: WebIM.config.appkey
	}
	return WebIM.conn.open(options);
}


IM.prototype.setUserInfo = function() {
	console.log(this.userInfo)
	let options = {
		nickname: this.userInfo.nickname,
		avatarurl: this.userInfo.avatars,
		phone: this.userInfo.phone,
	}
	return WebIM.conn.updateOwnUserInfo(options);
}

IM.prototype.getType = function(chatType) {
	console.log(chatType)
	if (chatType == 'groupchat') {
		return 'groupChat'
	} else {
		return 'singleChat'
	}
}

IM.prototype.getSessionList = function() {
	return WebIM.conn.getSessionList()
}

IM.prototype.getId = function(id) {
	return id.split("_")[1].split("@")[0];
}

IM.prototype.getChatType = function(channelId) {
	if (channelId.split('@')[1] == 'conference.easemob.com') {
		return 'groupChat'
	} else if (channelId.split('@')[1] == 'easemob.com') {
		return 'singleChat'
	}
}

IM.prototype.createChannelIdBySessionId = function(sessionId, chatType) {
	if (chatType == 'groupChat') {
		return `${WebIM.config.appkey}_${sessionId}@conference.easemob.com`
	} else {
		return `${WebIM.config.appkey}_${sessionId}@easemob.com`
	}

}

IM.prototype.fetchHistoryMessages = function({
	sessionId,
	messageCount,
	isGroup,
	start
}) {
	let options = {
		queue: sessionId.toLowerCase(),
		isGroup,
		count: messageCount,
		start: start ? JSON.parse(JSON.stringify(start)).id : '',
		success: (res) => {
			console.log('获取漫游消息成功', res)
		},
		fail: (err) => {
			console.log('获取漫游消息失败', err)
			this.vm.$showToast('拉取历史消息失败');
		}
	}
	console.log(options.start)
	return WebIM.conn.fetchHistoryMessages(options)
}


IM.prototype.msgCache = function() {
	return WebIM.conn.mr_cache = [];
}

IM.prototype.sendTextMsg = function({
	textValue,
	receiverId,
	chatType,
	payload
}) {
	let _this = this;
	return new Promise((resolve, reject) => {
		// 生成本地消息id
		let id = WebIM.conn.getUniqueId();
		// 创建文本消息
		let msg = new WebIM.message("txt", id);
		msg.set({
			msg: textValue,
			to: receiverId,
			chatType: chatType,
			ext: payload,
			success: (id, serverMsgId) => {
				console.log(id)
				console.log(serverMsgId)
				_this.vm.$set(localTextMessage, 'status', 'success');
				_this.vm.$set(localTextMessage, 'mid', serverMsgId);
				resolve(localTextMessage);
			},
			fail: (e) => {
				console.log('发送失败', e)
				_this.vm.$set(localTextMessage, 'status', 'fail');
				_this.vm.$set(localTextMessage, 'error', true);
				_this.vm.$showToast('发送失败')
				reject(localTextMessage)
			},
		});
		console.log(msg.body);

		let localTextMessage = _this.createLocalTextMsg(msg.body);

		// uni.getNetworkType({
		// 	success: (res) => {
		// 		if (res.networkType == 'none') {
		// 			console.log('发送失败', e)
		// 			_this.vm.$set(localTextMessage, 'status', 'fail');
		// 			_this.vm.$set(localTextMessage, 'error', true);
		// 			_this.vm.$showToast('无网络,发送失败')
		// 			return reject(localTextMessage)
		// 		}
		// 	}
		// });

		if (this.vm.networkStatus == 'none') {
			_this.vm.$set(localTextMessage, 'status', 'fail');
			_this.vm.$set(localTextMessage, 'error', true);
			_this.vm.$showToast('无网络,发送失败')
			return reject(localTextMessage)
		}

		console.log(this.vm.networkStatus);
		WebIM.conn.send(msg.body);




		console.log(localTextMessage)
	})
}

IM.prototype.createLocalTextMsg = function(msg) {
	let localTextMessage = {
		contentsType: 'TEXT',
		data: msg.msg,
		from: this.userId,
		id: msg.id,
		time: msg.time,
		to: msg.to,
		mid: '',
		status: 'sending',
		error: false,
		ext: msg.ext,
		// type: msg.chatType == 'singleChat' ? 'chat' : 'groupChat',
		type: msg.chatType,
	}
	return localTextMessage
}

IM.prototype.sendImageMsg = function({
	filePath,
	receiverId,
	chatType,
	payload
}) {
	return new Promise(async (resolve, reject) => {

		try {
			const _this = this;
			const {
				width,
				height,
				index,
				filetype
			} = await this.getImageInfo(filePath);

			const data = await this.upload(filePath, 'image')
			console.log(data)
			const dataObj = JSON.parse(data);
			console.log(dataObj)
			const file = {
				type: 'img',
				size: {
					width: width,
					height: height
				},
				// url: dataObj.uri + "/" + dataObj.entities[0].uuid,
				url: dataObj.data.file_url,
				filetype: filetype,
				filename: filePath
			};
			console.log(file)
			const id = WebIM.conn.getUniqueId();
			const msg = new WebIM.message('img', id);
			msg.set({
				apiUrl: WebIM.config.apiURL,
				body: file,
				from: this.userId,
				to: receiverId,
				roomType: false,
				chatType,
				ext: payload,
				success: (res, mid) => {
					console.log(res)
					console.log(mid)
					_this.vm.$set(localImageMsg, 'status', 'success');
					_this.vm.$set(localImageMsg, 'mid', mid);
					resolve(localImageMsg)
				},
				fail: (err) => {
					console.log(err)
					_this.vm.$showToast('发送失败')
					_this.vm.$set(localImageMsg, 'status', 'fail');
					_this.vm.$set(localImageMsg, 'error', true);
					reject(localImageMsg)
				}
			});



			console.log(msg.body);
			WebIM.conn.send(msg.body);

			let localImageMsg = this.createLocalImageMsg(msg.body);
		} catch (err) {
			reject(localImageMsg)
			this.$showToast('发送失败')
		}
	})
}

IM.prototype.getImageInfo = function(imagePath) {
	return new Promise((resolve, reject) => {
		var _this = this;
		uni.getImageInfo({
			src: imagePath,
			success: (res) => {
				const width = res.width;
				const height = res.height;
				const index = res.path.lastIndexOf(".");
				const filetype = ~index && res.path.slice(index + 1) || "";
				if (res.type && filetype.toLowerCase() in this.imageAllowType || res.type in
					this.imageAllowType) {
					resolve({
						width,
						height,
						index,
						filetype
					})
				} else {
					reject()
					_this.vm.$showToast('暂不支持该类型图片');
				}
			},
			fail: (err) => {
				reject()
				_this.vm.$showToast('获取图片信息失败')
			}
		})
	})
}

IM.prototype.upload = function(imagePath, fileType) {
	return new Promise((resolve, reject) => {
		try {
			uni.showLoading({
				title: `${fileType == 'image' ? '图片' : fileType == 'audio' ? '语音' : '视频'}上传中`
			})
			const _this = this;
			// const token = WebIM.conn.context.accessToken;
			// const str = WebIM.config.appkey.split("#");
			uni.uploadFile({
				// url: "https://a1.easemob.com/" + str[0] + "/" + str[1] +
				// 	"/chatfiles",
				url: "https://www.gdlzjt.com/api/upload/uploadFileCos",
				filePath: imagePath,
				fileType,
				name: "file",
				header: {
					// "Content-Type": "multipart/form-data",
					'Content-Type': 'application/x-www-form-urlencoded',
					// Authorization: "Bearer " + token
					"UserToken": _this.vm.getTokenSync(),
				},
				success: (result) => {
					uni.hideLoading()
					console.log(result)
					if (result.statusCode == 400) {
						_this.vm.$showToast('文件不合法');
						reject()
					} else {
						resolve(result.data)
					}
				},
				fail: (error) => {
					uni.hideLoading()
					_this.vm.$showToast('上传文件失败');
					reject()
				}
			})
		} catch (e) {
			uni.hideLoading()
			reject()
		}
	})
}

IM.prototype.createLocalImageMsg = function(msg) {
	let localImageMsg = {
		contentsType: 'IMAGE',
		from: msg.from,
		url: msg.body.url,
		time: msg.time,
		to: msg.to,
		type: msg.chatType,
		ext: msg.ext,
		error: false,
		status: 'sending',
		id: msg.id,
		mid: '',
	}
	return localImageMsg
}

IM.prototype.sendFileMessage = function({
	fileInfo,
	receiverId,
	chatType,
	payload
}) {
	return new Promise((resolve, reject) => {
		console.log(fileInfo)
		console.log(payload)
		var id = WebIM.conn.getUniqueId(); // 生成本地消息id
		var msg = new WebIM.message('custom', id); // 创建自定义消息

		const file = {
			filesize: fileInfo.size,
			url: fileInfo.file_url,
			filename: fileInfo.name,
		}


		msg.set({
			to: receiverId, // 接收消息对象（用户id）
			customExts: file,
			ext: payload,
			chatType, // 设置聊天类型 单聊 群聊 聊天室
			success: (res, mid) => {
				console.log(res)
				this.vm.$set(localCustomMsg, 'status', 'success');
				this.vm.$set(localCustomMsg, 'mid', mid);
				resolve(localCustomMsg)
			},
			fail: (err) => {
				console.log(err)
				this.vm.$showToast('发送失败');
				this.vm.$set(localCustomMsg, 'error', true);
				this.vm.$set(localCustomMsg, 'status', 'fail');
				reject(localCustomMsg)
			}
		});

		console.log(msg.body)
		WebIM.conn.send(msg.body)
		let localCustomMsg = this.createLocalCustomMsg(msg.body, 'FILE')
	})
}

IM.prototype.createLocalCustomMsg = function(msg, type) {
	console.log(msg)
	let localCustomMsg = {
		contentsType: type,
		from: this.userId,
		to: msg.to,
		customExts: msg.customExts,
		time: msg.time,
		id: msg.id,
		ext: msg.ext,
		error: false,
		status: 'sending',
		type: msg.chatType,
		mid: '',
	}
	return localCustomMsg
}

IM.prototype.getGroupInfo = function(groupId) {
	let options = {
		groupId, // 群组id
	};
	return WebIM.conn.getGroupInfo(options)
}

IM.prototype.getSingleUserInfo = function(userId) {
	return WebIM.conn.fetchUserInfoById(userId);
}

IM.prototype.sendLocationMsg = function({
	locationInfo,
	receiverId,
	chatType,
	payload
}) {
	return new Promise((resolve, reject) => {
		const id = WebIM.conn.getUniqueId();
		const msg = new WebIM.message('custom', id);


		msg.set({
			to: receiverId, // 接收消息对象（用户id）
			customExts: locationInfo,
			ext: payload,
			chatType, // 设置聊天类型 单聊 群聊 聊天室
			success: (res, mid) => {
				console.log(res)
				this.vm.$set(localCustomMsg, 'status', 'success');
				this.vm.$set(localCustomMsg, 'mid', mid);
				resolve(localCustomMsg)
			},
			fail: (err) => {
				console.log(err)
				this.vm.$showToast('发送失败');
				this.vm.$set(localCustomMsg, 'error', true);
				this.vm.$set(localCustomMsg, 'status', 'fail');
				reject(localCustomMsg)

			}
		});

		let localCustomMsg = this.createLocalCustomMsg(msg.body, 'LOCATION')

		if (this.vm.networkStatus == 'none') {
			_this.vm.$set(localCustomMsg, 'status', 'fail');
			_this.vm.$set(localCustomMsg, 'error', true);
			_this.vm.$showToast('无网络,发送失败')
			return reject(localCustomMsg)
		}

		WebIM.conn.send(msg.body)

	})
}

IM.prototype.withdrawMsg = function({
	id,
	receiverId,
	chatType
}) {
	const _this = this;
	const options = {
		mid: id,
		to: receiverId,
		type: chatType.toLowerCase(),
		success: () => {
			console.log('撤回成功')
		},
		fail: () => {
			console.log('撤回失败')
			_this.vm.$showToast('撤回失败');
		}
	}


	return WebIM.conn.recallMessage(options);
}

IM.prototype.sendWithdrawCallbackMsg = function({
	receiverId,
	chatType,
	payload,
}) {
	return new Promise((resolve, reject) => {
		const id = WebIM.conn.getUniqueId();
		const msg = new WebIM.message('custom', id);

		msg.set({
			to: receiverId,
			ext: payload,
			chatType,
			success: (res, mid) => {
				console.log(res)
				this.vm.$set(localCustomMsg, 'status', 'success');
				this.vm.$set(localCustomMsg, 'mid', mid);
				resolve(localCustomMsg)
			},
			fail: (err) => {
				console.log(err)
				this.vm.$showToast('发送失败');
				this.vm.$set(localCustomMsg, 'error', true);
				this.vm.$set(localCustomMsg, 'status', 'fail');
				reject(localCustomMsg)
			}
		});

		WebIM.conn.send(msg.body)
		let localCustomMsg = this.createLocalCustomMsg(msg.body, 'withdraw')
	})
}

IM.prototype.sendVoiceMsg = function({
	filePath,
	duration,
	receiverId,
	chatType,
	payload,
}) {
	return new Promise(async (resolve, reject) => {
		try {
			const data = await this.upload(filePath, 'audio');
			const dataObj = JSON.parse(data);
			console.log(JSON.parse(data));
			const id = WebIM.conn.getUniqueId(); // 生成本地消息id
			const msg = new WebIM.message('audio', id);
			const token = WebIM.conn.context.accessToken;
			msg.set({
				apiUrl: WebIM.config.apiURL,
				accessToken: token,
				body: {
					type: 'audio',
					// url: dataObj.uri + "/" + dataObj.entities[0].uuid,
					url: dataObj.data.file_url,
					filetype: "",
					filename: filePath,
					accessToken: token,
					length: Math.ceil(duration / 1000)
				},
				from: this.userId,
				to: receiverId,
				roomType: false,
				chatType: chatType,
				ext: payload,
				success: (res, mid) => {
					console.log(res)
					this.vm.$set(localVoiceMsg, 'status', 'success');
					this.vm.$set(localVoiceMsg, 'mid', mid);
					resolve(localVoiceMsg)

				},
				fail: (err) => {
					console.log(err)
					this.vm.$set(localVoiceMsg, 'status', 'error');
					this.vm.$set(localVoiceMsg, 'error', false);
					this.vm.$showToast('发送失败');
					reject(localVoiceMsg)
				}
			});
			WebIM.conn.send(msg.body);
			console.log(msg.body);

			let localVoiceMsg = this.createLocalVoiceMsg(msg.body);

		} catch (err) {
			console.log(err)
			this.vm.$set(localVoiceMsg, 'status', 'error');
			this.vm.$set(localVoiceMsg, 'error', false);
			reject(localVoiceMsg);
			this.vm.$showToast('发送失败');
		}

	})
}

IM.prototype.createLocalVoiceMsg = function(msg) {
	let localVoiceMsg = {
		id: msg.id,
		chatType: msg.chatType,
		to: msg.to,
		from: msg.from,
		time: msg.time,
		url: msg.body.url,
		length: msg.body.length,
		ext: msg.ext,
		error: false,
		status: 'sending',
		type: msg.chatType,
		mid: '',
	}
	return localVoiceMsg
}

IM.prototype.sendVideoMsg = function({
	videoInfo,
	receiverId,
	chatType,
	payload,
}) {
	return new Promise(async (resolve, reject) => {
		console.log(videoInfo)
		try {
			uni.showLoading({
				title: '正在上传视频'
			})
			const id = WebIM.conn.getUniqueId();
			const token = WebIM.conn.context.accessToken;
			const url = await this.uploadvideo(videoInfo.tempFilePath,
				`${id}.${videoInfo.tempFilePath.split('.')[videoInfo.tempFilePath.split('.').length-1]}`
			);
			console.log(url)

			let msg = new WebIM.message('custom', id);

			msg.set({
				to: receiverId, // 接收消息对象（用户id）
				customExts: {
					...videoInfo,
					url,
				},
				ext: payload, // 消息扩展
				chatType,
				success: (res) => {
					uni.hideLoading()
					console.log(res)
					this.vm.$set(localVideoMsg, 'status', 'success');
					resolve(localVideoMsg)
				},
				fail: (err) => {
					uni.hideLoading()
					console.log(err)
					this.vm.$shotToast('发送失败')
					this.vm.$set(localVideoMsg, 'status', 'fail');
					this.vm.$set(localVideoMsg, 'error', true);
					reject(localVideoMsg)
				}
			});
			console.log(msg.body);
			WebIM.conn.send(msg.body);
			let localVideoMsg = this.createLocalCustomMsg(msg.body, 'VIDEO');

		} catch (e) {
			uni.hideLoading()
			console.log(e)
			reject();
			this.vm.$showToast('发送失败');
		}
	})
}
IM.prototype.uploadvideo = function(filePath, fileName) {
	console.log(filePath)
	console.log(fileName)
	return new Promise((resolve, reject) => {
		uniCloud.uploadFile({
			filePath: filePath,
			cloudPath: fileName,
			success(res) {
				console.log(res)
				resolve(res.fileID);
			},
			fail(err) {
				console.log(Error)
				reject();
			},
		})
	})
}

IM.prototype.setSessionRead = function(sessionId, chatType) {
	const msg = new WebIM.message('channel', WebIM.conn.getUniqueId());
	if (chatType == 'groupChat') {
		msg.set({
			to: sessionId,
			chatType: 'groupChat'
		});
	} else {
		msg.set({
			to: sessionId
		});
	}
	return WebIM.conn.send(msg.body);
}

IM.prototype.createSession = function({
	channelId,
	sessionId, //必填
	lastMsg,
	messageType,
	userName,
	unreadNum,
	chatType, //必填
	time,
	sessionName
}) {
	let sessionTemp = {
		channelId: channelId ? channelId : this.createChannelIdBySessionId(sessionId, chatType),
		sessionId,
		lastMsg,
		messageType,
		userName,
		unreadNum: unreadNum ? unreadNum : 0,
		chatType,
		time,
		sessionName,
	}
	return sessionTemp
}

IM.prototype.isSender = function({
	msgFromId
}) {
	return msgFromId == this.userId;
}

IM.prototype.getLastMsgByMsgType = function(msg) {
	const msgType = msg.ext.messageType;
	if (msgType == 'image') {
		return '[图片]'
	} else if (msgType == 'file') {
		return '[文件]'
	} else if (msgType == 'voice') {
		return '[语音]'
	} else if (msgType == 'video') {
		return '[视频]'
	} else if (msgType == 'text') {
		return msg.data
	} else if (msgType == 'withdraw') {
		return `${msg.ext.userName}撤回了一条消息`
	}
}

export default IM
